<template>
  <view class="message-consult-page">
    <!-- 咨询留言列表区域 -->
    <view class="message-list-container">
      <z-paging
        ref="paging"
        v-model="messageList"
        @query="queryList"
        :auto="true"
        :refresher-enabled="true"
        :loading-more-enabled="true"
        :empty-view-text="'暂无数据'"
        class="message-list"
      >
        <template #top>
          <!-- 导航栏 -->
          <up-navbar title="我处理的咨询留言" :autoBack="true" :fixed="true" bgColor="transparent" :border="false" placeholder/>
          
          <!-- 筛选器区域 -->
          <view class="filter-section">
            <view class="filter-row">
              <view class="filter-item">
                <picker mode="selector" :value="filters.statusIndex" :range="statusOptions" range-key="text" @change="onStatusChange">
                  <view class="picker-text">
                    <text>{{ filters.statusIndex >= 0 ? statusOptions[filters.statusIndex].text : '处理状态' }}</text>
                    <up-icon name="arrow-down" size="14"></up-icon>
                  </view>
                </picker>
              </view>
              <view class="filter-item date-picker">
                <picker mode="date" :value="filters.date" @change="onDateChange">
                  <view class="picker-text">
                    <text>{{ filters.date || '选择日期' }}</text>
                    <up-icon name="calendar" size="14"></up-icon>
                  </view>
                </picker>
              </view>
            </view>
            <view class="filter-row">
              <view class="filter-item search-item">
                <up-search
                  v-model="filters.searchKeyword"
                  :clearabled="true"
                  :showAction="true"
                  placeholder="请输入用户手机号或回复内容"
                  @search="handleSearch"
                  @clear="handleClear"
                >
                  <template #action>
                    <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                  </template>
                </up-search>
              </view>
            </view>
          </view>
        </template>
        <view class="message-list-content">
          <message-item
            v-for="item in messageList"
            :key="item.id"
            :message="item"
            @reply="handleReply"
            @view="handleView"
          />
        </view>
      </z-paging>
    </view>
    
    <!-- 回复弹窗 -->
    <up-popup
      v-model="showReplyPopup"
      mode="center"
      width="80%"
      :round="10"
      :closeable="true"
      @close="closeReplyPopup"
    >
      <view class="reply-popup">
        <view class="popup-title">回复留言</view>
        <view class="popup-content">
          <view class="message-info">
            <view class="info-row">
              <text class="label">用户手机：</text>
              <text class="value">{{ currentMessage?.userPhone || '-' }}</text>
            </view>
            <view class="info-row">
              <text class="label">留言内容：</text>
              <text class="value">{{ currentMessage?.content || '-' }}</text>
            </view>
          </view>
          <view class="reply-input">
            <textarea
              v-model="replyContent"
              placeholder="请输入回复内容"
              :maxlength="200"
              class="textarea"
            />
            <view class="word-count">{{ replyContent.length }}/200</view>
          </view>
        </view>
        <view class="popup-footer">
          <up-button type="info" @click="closeReplyPopup">取消</up-button>
          <up-button type="primary" @click="submitReply" :disabled="!replyContent.trim()">确认回复</up-button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import MessageItem from './components/MessageItem.vue'

// 筛选条件
const filters = reactive({
  statusIndex: 0,
  date: '',
  searchKeyword: ''
})

// 下拉选项数据
const statusOptions = [
  { value: '', text: '全部状态' },
  { value: 'pending', text: '待回复' },
  { value: 'replied', text: '已回复' }
]

// 列表数据
const messageList = ref([])
const paging = ref(null)

// 回复弹窗相关
const showReplyPopup = ref(false)
const currentMessage = ref(null)
const replyContent = ref('')

// 获取咨询留言列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 获取筛选条件的值
    const params = {
      status: filters.statusIndex === 0 ? undefined : statusOptions[filters.statusIndex].value,
      date: filters.date,
      searchKeyword: filters.searchKeyword,
      pageNum: pageNo,
      pageSize
    }

    // TODO: 替换为实际的API调用
    const response = await new Promise(resolve => {
      setTimeout(() => {
        // 模拟数据筛选
        let mockData = [
          {
            id: '1',
            userPhone: '13800138000',
            content: '请问我的车辆年检什么时候到期？',
            status: 'pending',
            createTime: '2024-03-15 10:30:00'
          },
          {
            id: '2',
            userPhone: '13900139000',
            content: '我想了解一下办理临时通行证的流程',
            status: 'replied',
            createTime: '2024-03-15 09:15:00',
            replyContent: '您好，临时通行证可以在我们的官方APP上申请，需要提供车辆行驶证、驾驶证等证件信息。',
            replyTime: '2024-03-15 11:20:00'
          },
          {
            id: '3',
            userPhone: '13700137000',
            content: '我的车辆被贴了违停告知单，但我并没有违停',
            status: 'replied',
            createTime: '2024-03-14 08:00:00',
            replyContent: '您好，请提供违停告知单号和车牌号，我们会核实处理。',
            replyTime: '2024-03-14 09:30:00'
          },
          {
            id: '4',
            userPhone: '13600136000',
            content: '请问如何申请居民停车证？',
            status: 'pending',
            createTime: '2024-03-14 07:45:00'
          },
          {
            id: '5',
            userPhone: '13500135000',
            content: '我想咨询一下关于新能源车辆的优惠政策',
            status: 'replied',
            createTime: '2024-03-13 06:30:00',
            replyContent: '您好，目前新能源车辆可享受免费停车2小时的优惠，详情可查看我们官网的政策公告。',
            replyTime: '2024-03-13 08:15:00'
          }
        ]

        // 根据状态筛选
        if (params.status) {
          mockData = mockData.filter(item => item.status === params.status)
        }

        // 根据日期筛选
        if (params.date) {
          mockData = mockData.filter(item => item.createTime.startsWith(params.date))
        }

        // 根据关键词筛选（用户手机、回复内容）
        if (params.searchKeyword) {
          const keyword = params.searchKeyword.toLowerCase()
          mockData = mockData.filter(item => 
            item.userPhone.includes(keyword) ||
            (item.replyContent && item.replyContent.toLowerCase().includes(keyword))
          )
        }

        resolve({
          data: mockData,
          total: mockData.length
        })
      }, 1000)
    })
    
    paging.value.complete(response.data)
  } catch (error) {
    console.error('获取咨询留言列表失败:', error)
    uni.showToast({
      title: '获取数据失败',
      icon: 'none'
    })
    paging.value.complete(false)
  }
}

// 处理筛选条件变化
const onStatusChange = (e) => {
  filters.statusIndex = parseInt(e.detail.value)
  paging.value.reload()
}

// 处理日期变化
const onDateChange = (e) => {
  filters.date = e.detail.value
  paging.value.reload()
}

// 处理搜索
const handleSearch = () => {
  paging.value.reload()
}

// 处理清空搜索
const handleClear = () => {
  filters.searchKeyword = ''
  paging.value.reload()
}

// 处理回复留言
const handleReply = (message) => {
  currentMessage.value = message
  replyContent.value = ''
  showReplyPopup.value = true
}

// 关闭回复弹窗
const closeReplyPopup = () => {
  showReplyPopup.value = false
}

// 提交回复
const submitReply = () => {
  if (!replyContent.value.trim()) {
    uni.showToast({
      title: '请输入回复内容',
      icon: 'none'
    })
    return
  }

  // TODO: 调用回复API
  uni.showLoading({
    title: '提交中...'
  })

  setTimeout(() => {
    uni.hideLoading()
    uni.showToast({
      title: '回复成功',
      icon: 'success'
    })
    showReplyPopup.value = false
    paging.value.reload()
  }, 1500)
}

// 处理查看详情
const handleView = (message) => {
  uni.navigateTo({
    url: `/pages/message-consult/detail/index?id=${message.id}`
  })
}

// 页面加载时获取数据
onMounted(() => {
  paging.value.reload()
})
</script>

<style lang="scss" scoped>
.message-consult-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.filter-section {
  background-color: #ffffff;
  padding: 12px;
  border-radius: 12rpx;
  margin: 12px;
  
  .filter-row {
    display: flex;
    gap: 12px;
    align-items: center;
    margin-bottom: 12px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .filter-item {
      flex: 1;
      
      .picker-text {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 8px 12px;
        background-color: #f5f5f5;
        border-radius: 4px;
        
        text {
          font-size: 14px;
          color: #333;
        }
      }
      
      &.search-item {
        flex: 1;
      }
    }
  }
}

.message-list-container {
  flex: 1;
  
  .message-list {
    height: 100%;
  }
  
  .message-list-content {
    padding: 12px;
  }
}

.reply-popup {
  padding: 20px;
  
  .popup-title {
    font-size: 18px;
    font-weight: bold;
    text-align: center;
    margin-bottom: 20px;
  }
  
  .popup-content {
    margin-bottom: 20px;
    
    .message-info {
      background-color: #f5f5f5;
      padding: 12px;
      border-radius: 4px;
      margin-bottom: 16px;
      
      .info-row {
        display: flex;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 14px;
          color: #666;
          width: 80px;
          flex-shrink: 0;
        }
        
        .value {
          font-size: 14px;
          color: #333;
          flex: 1;
        }
      }
    }
    
    .reply-input {
      position: relative;
      
      .textarea {
        width: 100%;
        height: 120px;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        box-sizing: border-box;
      }
      
      .word-count {
        position: absolute;
        right: 10px;
        bottom: 10px;
        font-size: 12px;
        color: #999;
      }
    }
  }
  
  .popup-footer {
    display: flex;
    justify-content: space-between;
    gap: 16px;
    
    .up-button {
      flex: 1;
    }
  }
}
</style>